package buttons.view;

import java.util.ArrayList;

import buttons.MenuItem;
import buttons.PopUpMenu;
import processing.core.PApplet;
import processing.core.PFont;
import view.V_DisplayObject;

public class V_PopUpMenu extends V_DisplayObject
{
  private PopUpMenu parent;
  private PApplet bigParent;
  private PFont font; 
  private int fontSize = 11;
  private String defaultFontName = "Verdana-10";
  private float pad = 6; // space between components
  private float indent = 10;
  private int highlightIndex = -1;
  
  public V_PopUpMenu(PopUpMenu p)
  {
    parent = p;
    xSize = 30;
    ySize = 200;
    visible = false;
  }
  
  //enable the use of the font by passing in the PApplet:
  public void useFont(PApplet p){
	  font = p.createFont(defaultFontName, fontSize);
	  bigParent = p;
  }
  
  public void display(PApplet p)
  {
    ArrayList<MenuItem> items = parent.getMenuItems();
    if(visible)
    {
      p.stroke(190);
      p.fill(255);
      ySize = (items.size())*(fontSize+pad)+pad;
      p.rect(xLoc, yLoc, xSize, ySize);
      // draw items:
      p.textFont(font);
      float bump = 0;
      for(int i = 0; i < items.size(); i++)
      {
        p.fill(0);
        bump += fontSize+pad;
        if (highlightIndex == i)
        {
          p.fill(100, 100, 255, 100);
          p.noStroke();
          p.rect(xLoc, yLoc+bump-fontSize-pad/2, xSize, fontSize+pad+pad/2);
          p.fill(255);
        }
        p.text(items.get(i).getContents(), xLoc+indent, yLoc+bump);
      }
    }// end of if(visible)
  }
  
  // re-size the panel depending on if this is larger than the current xSize or not.
  public void calcWidth(MenuItem item)
  {
	bigParent.textFont(font);
    float totalWidth = ((PApplet) bigParent).textWidth(item.getContents())+indent+indent;
    if(totalWidth > xSize) xSize = totalWidth;
  }
  
  public void checkOver(float mX, float mY)
  { // first check the greater bounds:
    if(mX > xLoc && mX < xLoc+xSize && mY > yLoc && mY < yLoc+ySize)
    { // now determine the index the mouse is over (only need to compare the Y)
      ArrayList<MenuItem> items = parent.getMenuItems();
      float bump = 0;
      for(int i = 0; i < items.size(); i++) {
        if(mY > yLoc+bump && mY < yLoc+bump+fontSize+pad) {
          highlightIndex = i;
          return;
        }
        bump += fontSize+pad;
      }
    }
    highlightIndex = -1;
  }// end of checkOver(..)
  
  public int getHighlightIndex()
  {
    return highlightIndex;
  }
}
